package com.javaziliao.design.items.vistor;

import com.javaziliao.design.items.composite.AbstractProductItem;
import com.javaziliao.design.items.composite.ProductComposite;
import com.javaziliao.design.utils.RedisCommonProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class DelItemVistor implements ItemVistor<AbstractProductItem> {
    @Autowired
    private RedisCommonProcessor redisProcessor;

    @Override
    public AbstractProductItem vistor(AbstractProductItem productItem) {
        ProductComposite currentItem = (ProductComposite) redisProcessor.get("items");
        ProductComposite delItem = (ProductComposite) productItem;
        if (delItem.getId() == currentItem.getId()) {
            throw new UnsupportedOperationException("根节点不能删除");
        }
        if (delItem.getPid() == currentItem.getId()) {
            currentItem.delProductChild(delItem);
            return currentItem;
        }
        delChild(delItem, currentItem);
        return currentItem;
    }

    private void delChild(ProductComposite delItem, ProductComposite currentItem) {
        for (AbstractProductItem child : currentItem.getChild()) {
            ProductComposite childItem = (ProductComposite) child;
            if (childItem.getId() == delItem.getPid()) {
                childItem.delProductChild(delItem);
                break;
            } else {
                delChild(delItem, childItem);
            }
        }
    }
}
